package com.smile.component;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2021/10/11 09:18
 */
@Component
public class RedisUtil {
    private  final RedisTemplate redisTemplate;

    public RedisUtil(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取缓存
     * @param key
     * @return
     */
    public Object getCacheByKey(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     * @param key   键
     * @param value 值
     */
    public void setCache(String key, Object value,long time) {
        redisTemplate.opsForValue().set(key, value,time,TimeUnit.SECONDS);
    }


    /**
     * 旁路缓存 闭包函数形式
     * @param key
     * @param closure
     * @param <K>
     * @param <V>
     * @return
     */
    public <K, V> Object getCacheByKeyInCacheAside1(K key,long expireTime, Closure<V, K> closure) {
        System.out.println("getCacheByKeyInCacheAside1 key:"+key);
        Object ret = getCacheByKey(key.toString());
        if (ret == null) {
            Object r = closure.execute(key);
            setCache(key.toString(), r.toString(),expireTime);
            return r;
        }
        return ret;
    }

    /**
     * lambda 形式
     * @param key
     * @param expireTime
     * @param supplier
     * @param <K>
     * @param <V>
     * @return
     */
    public <K, V> Object getCacheByKeyInCacheAside2(K key,long expireTime,Supplier supplier) {
        System.out.println("getCacheByKeyInCacheAside2 key:"+key);
        Object ret = getCacheByKey(key.toString());
        if (ret == null) {
            Object res = supplier.get();
            setCache(key.toString(), res.toString(),expireTime);
            return res;
        }
        return ret;
    }





}
